package cn.edu.hbwe.book.service;

import java.sql.SQLException;
import java.util.List;
import cn.edu.hbwe.book.dao.BookDao;
import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.entity.PageBean;
import cn.edu.hbwe.book.exception.FindBookByIdException;

public class BookService {

	public Book findBookById(String id) throws FindBookByIdException {
		BookDao dao = new BookDao();
		try {
			Book book = dao.findBookById(id);
			return book;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new FindBookByIdException("所查询的图书不存在！");
		}
	}

	// 分页操作
	public PageBean findBookByPage(int currentPage, int currentCount, String category) {
		PageBean bean = new PageBean();
		BookDao dao = new BookDao();
		// 封装每页显示数据条数
		bean.setCurrentCount(currentCount);
		// 封装当前页码
		bean.setCurrentPage(currentPage);
		// 封装当前查找类别
		bean.setCategory(category);
		try {
			// 获取总条数
			int totalCount = dao.findAllCount(category);
			bean.setTotalCount(totalCount);
			// 获取总页数
			int totalPage = (int) Math.ceil(totalCount * 1.0 / currentCount);
			bean.setTotalPage(totalPage);
			// 获取当前页数据
			List<Book> ps = dao.findByPage(currentPage, currentCount, category);
			bean.setPs(ps);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return bean;
	}

	//用于搜索框根据书名来模糊查询相应的图书
	public PageBean findBookByName(int currentPage, int currentCount, String searchfield) {
		PageBean bean = new PageBean();
		BookDao dao = new BookDao();
		// 封装每页显示数据条数
		bean.setCurrentCount(currentCount);
		// 封装当前页码
		bean.setCurrentPage(currentPage);
		// 封装模糊查询的图书名
		bean.setSearchfield(searchfield);
		try {
			// 获取总条数
			int totalCount = dao.findBookByNameAllCount(searchfield);
			bean.setTotalCount(totalCount);

			// 获取总页数
			int totalPage = (int) Math.ceil(totalCount * 1.0 / currentCount);
			bean.setTotalPage(totalPage);

			// 满足条件的图书
			List<Book> ps = dao.findBookByName(currentPage, currentCount, searchfield);
			bean.setPs(ps);
			return bean;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("根据书名查询图书失败！");
		}
	}

		//获取本周热销商品
		public List<Object[]> getWeekHotBook() {
			BookDao dao = new BookDao();
			try {
				return dao.getWeekHotBook();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("获取本周热销商品失败！");
			}
		}
}
